import Toast from 'tdesign-miniprogram/toast/index';
import requestApi from "../../../../utils/request"


const obj2Params = (obj = {}, encode = false) => {
  const result = [];
  Object.keys(obj).forEach((key) =>
    result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`),
  );

  return result.join('&');
};

Page({
  data: {
    commentsList: [],
    commentsStatistics: {
      badCount: 0,
      commentCount: 0,
      goodCount: 0,
      goodRate: 0,
      hasImageCount: 0,
      middleCount: 0,
    },
    isShowPromotionPop: false,
    activityList: [],
    details: {},
    goodsTabArray: [
      {
        name: '商品',
        value: '', // 空字符串代表置顶
      },
      {
        name: '详情',
        value: 'goods-page',
      },
    ],
    storeName: '',
    jumpArray: [
      {
        title: '首页',
        url: '/pages/shop/shop',
        iconName: 'wap-home',
      },
      {
        title: '购物车',
        url: '/service/shoppingMall/Cart/index',
        iconName: 'cart',
        showCartNum: true,
      },
      // {
      //   title: '分享',
      //   url: '/pages/cart/index',
      //   iconName: 'share',
      // },
    ],
    isStock: true,
    cartNum: 0,
    soldout: false,
    buttonType: 1,
    buyNum: 1,
    selectedAttrStr: '',
    skuArray: [],
    primaryImage: '',
    specImg: '',
    isSpuSelectPopupShow: false,
    isAllSelectedSku: false,
    buyType: 0,
    outOperateStatus: false, // 是否外层加入购物车
    operateType: 0,
    selectSkuSellsPrice: 0,
    maxLinePrice: 0,
    minSalePrice: 0,
    maxSalePrice: 0,
    list: [],
    spuId: '',
    navigation: { type: 'fraction' },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    soldNum: 0, // 已售数量
  },

  handlePopupHide() {
    this.setData({
      isSpuSelectPopupShow: false,
    });
  },

  showSkuSelectPopup(type) {
    this.setData({
      buyType: type || 0,
      outOperateStatus: type >= 1,
      isSpuSelectPopupShow: true,
    });
  },

  buyItNow() {
    this.showSkuSelectPopup(1);
  },

  toAddCart() {
    this.showSkuSelectPopup(2);
  },

  toNav(e) {
    const { url } = e.detail;
    if (url == '/pages/shop/shop') {
      wx.switchTab({
        url: url,
      });
    } else {
      wx.navigateTo({
        url: url,
      });
    }
  },

  showCurImg(e) {
    const { index } = e.detail;
    const { images } = this.data.details;
    wx.previewImage({
      current: images[index],
      urls: images, // 需要预览的图片http链接列表
    });
  },

  onPageScroll({ scrollTop }) {
    const goodsTab = this.selectComponent('#goodsTab');
    goodsTab && goodsTab.onScroll(scrollTop);
  },

  chooseSpecItem(e) {
    const { sku } = this.data.details;
    const { selectedSku, isAllSelectedSku } = e.detail;
    if (!isAllSelectedSku) {
      this.setData({
        selectSkuSellsPrice: 0,
      });
    }
    this.setData({
      isAllSelectedSku,
    });
    this.getSkuItem(sku, selectedSku);
  },

  getSkuItem(specList, selectedSku) {
    let specArr = []
    specList.forEach((item) => {
      if (item.content.length > 0) {
        item.content.forEach(n => {
          specArr.push(n)
        })
      }
    })
    const selectedSkuValues = this.getSelectedSkuValues(specList, selectedSku);
    this.setData({
      selectItem: selectedSkuValues,
    });
  },

  // 获取已选择的sku名称
  getSelectedSkuValues(skuTree, selectedSku) {
    const normalizedTree = this.normalizeSkuTree(skuTree);
    return Object.keys(selectedSku).reduce((selectedValues, skuKeyStr) => {
      const skuValues = normalizedTree[skuKeyStr];
      const skuValueId = selectedSku[skuKeyStr];
      if (skuValueId !== '') {
        const skuValue = skuValues.filter((value) => {
          return value.id === skuValueId;
        })[0];
        skuValue && selectedValues.push(skuValue);
      }
      return selectedValues;
    }, []);
  },

  normalizeSkuTree(skuTree) {
    const normalizedTree = {};
    skuTree.forEach((treeItem) => {
      normalizedTree[treeItem.id] = treeItem.content;
    });
    return normalizedTree;
  },

  selectSpecsName(selectSpecsName) {
    if (selectSpecsName) {
      this.setData({
        selectedAttrStr: selectSpecsName,
      });
    } else {
      this.setData({
        selectedAttrStr: '',
      });
    }
  },

  addCart(sapcList) {
    const { isAllSelectedSku } = this.data;
    const { selectItem, skuArray } = this.data;
    if (skuArray.length !== 1) {
      if (!isAllSelectedSku) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择规格',
          icon: '',
          duration: 1000,
        });
        return;
      }
    }
    this.handlePopupHide(sapcList);
    //选中规格筛选
    let checkArr = []
    let chaeckId = null
    if (selectItem) {
      selectItem.forEach(e => {
        checkArr.push(e.id)
      });
    }
    if (skuArray.length > 0) {
      skuArray.forEach(n => {
        let str = n.specInfo.join('')
        let check = checkArr.join('')
        if (str == check) {
          chaeckId = n.id
        }
      })
    }
    const query = {
      goods_id: sapcList.detail.limitBuyInfo.id,
      goods_num: sapcList.detail.buyNum,
      sku_price_id: chaeckId,
    };
    console.log(query)
    requestApi.post('shopro/cart/add', { goods_list: [query] }, true).then(res => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '加入购物车成功',
        icon: '',
        duration: 1000,
      });
    })
  },

  gotoBuy(sapcList) {
    const { isAllSelectedSku, selectItem, skuArray } = this.data;
    if (skuArray.length !== 1) {
      if (!isAllSelectedSku) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择规格',
          icon: '',
          duration: 1000,
        });
        return;
      }
    }

    this.handlePopupHide(sapcList);
    //选中规格筛选
    let checkArr = []
    let chaeckId = null
    if (selectItem) {
      selectItem.forEach(e => {
        checkArr.push(e.id)
      });
    }
    if (skuArray.length > 0) {
      skuArray.forEach(n => {
        let str = n.specInfo.join('')
        let check = checkArr.join('')
        if (str == check) {
          chaeckId = n.id
        }
      })
    }
    let newSpecList = sapcList.detail.specList
    const query = {
      goods_id: sapcList.detail.limitBuyInfo.id,
      goods_num: sapcList.detail.buyNum,
      sku_price_id: chaeckId,
    };
    let urlQueryStr = obj2Params({
      goodsRequestList: JSON.stringify([query]),
    });
    urlQueryStr = urlQueryStr ? `?${urlQueryStr}` : '';
    const path = `/service/shoppingMall/Order/order-confirm/index${urlQueryStr}`;
    wx.navigateTo({
      url: path,
    });
  },

  specsConfirm(sapcList) {
    const { buyType } = this.data;
    if (buyType === 1) {
      this.gotoBuy(sapcList);
    } else {
      this.addCart(sapcList);
    }
    // this.handlePopupHide();
  },

  changeNum(e) {
    this.setData({
      buyNum: e.detail.buyNum,
    });
  },

  closePromotionPopup() {
    this.setData({
      isShowPromotionPop: false,
    });
  },

  promotionChange(e) {
    const { index } = e.detail;
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${index}`,
    });
  },

  showPromotionPopup() {
    this.setData({
      isShowPromotionPop: true,
    });
  },

  getDetail(spuId) {
    requestApi.get('shopro/goods/detail', { id: spuId }, true).then(res => {
      let details = res.data
      const skuArray = [];
      const {
        sku_price,
        primaryImage,
        isPutOnSale,
        original_price,
        maxSalePrice,
        price,
        show_sales
      } = details;
      details.content = this.formatRichText(details.content)
      sku_price.forEach((item) => {
        skuArray.push({
          id: item.id,
          stock: item.stock,
          specInfo: item.goods_sku_id_arr,
        });
      });
      this.setData({
        details,
        // activityList,
        isStock: details.stock > 0,
        maxSalePrice: maxSalePrice ? parseInt(maxSalePrice) * 100 : 0,
        maxLinePrice: original_price ? parseInt(original_price) * 100 : 0,
        minSalePrice: price ? Number(price) * 100 : 0,
        // list: promotionArray,
        skuArray: skuArray,
        primaryImage,
        soldout: isPutOnSale === 0,
        show_sales,
      });
    })
  },
  //处理富文本图片宽度问题
  formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    return newContent;
  },
  async getCommentsList(data) {
    try {
      const code = 'Success';
      if (data.length > 0) {
        let newData = [data[0]]
        const nextState = {
          commentsList: newData.map((item) => {
            return {
              goodsSpu: item.spuId,
              userName: item.user.nickname || '',
              commentScore: item.level,
              commentContent: item.content || '用户未填写评价',
              userHeadUrl: item.user.avatar,
            };
          }),
        };
        this.setData(nextState);
      }
    } catch (error) {
      console.error('comments error:', error);
    }
  },

  onShareAppMessage() {
    // 自定义的返回信息
    const { selectedAttrStr } = this.data;
    let shareSubTitle = '';
    if (selectedAttrStr.indexOf('件') > -1) {
      const count = selectedAttrStr.indexOf('件');
      shareSubTitle = selectedAttrStr.slice(count + 1, selectedAttrStr.length);
    }
    const customInfo = {
      imageUrl: this.data.details.primaryImage,
      title: this.data.details.title + shareSubTitle,
      path: `/service/shoppingMall/Details/details/index?spuId=${this.data.spuId}`,
    };
    return customInfo;
  },

  /** 获取评价统计 */
  async getCommentsStatistics() {
    try {
      const code = 'Success';

      const { spuId } = this.data
      const params = {
        goods_id: spuId,
        type: 'all'
      }
      const data = await requestApi.get('shopro/goods_comment/index', params, true)
      if (data.code === 1) {
        const {
          badCount,
          commentCount,
          goodCount,
          goodRate,
          hasImageCount,
          middleCount,
        } = data;
        const nextState = {
          commentsStatistics: {
            badCount: parseInt(`${badCount}`),
            commentCount: data.data.data.length,
            goodCount: parseInt(`${goodCount}`),
            /** 后端返回百分比后数据但没有限制位数 */
            goodRate: Math.floor(goodRate * 10) / 10,
            hasImageCount: parseInt(`${hasImageCount}`),
            middleCount: parseInt(`${middleCount}`),
          },
        };
        this.setData(nextState);
        this.getCommentsList(data.data.data)
      }
    } catch (error) {
      console.error('comments statiistics error:', error);
    }
  },

  /** 跳转到评价列表 */
  navToCommentsListPage() {
    wx.navigateTo({
      url: `/service/shoppingMall/Goods/comments/index?spuId=${this.data.spuId}`,
    });
  },

  onLoad(query) {
    const { spuId } = query;
    this.setData({
      spuId: spuId,
    });
    this.getDetail(spuId);
    // this.getCommentsList(spuId);
    this.getCommentsStatistics(spuId);
  },
});
